import service from '@/services/user';
import { useCallback, useEffect, useState } from 'react';

export default () => {
  const { UserController } = service;
  const [data, setData] = useState<API.PageInfo_UserInfo_>({});
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  // 使用 useCallback 缓存函数避免不必要的重新创建
  const fetchUserList = useCallback(
    async (
      params: {
        keyword?: string;
        current?: number;
        pageSize?: number;
      } = {},
      options: { [key: string]: any } = {},
    ) => {
      setLoading(true);
      setError(null);

      try {
        const userList = await UserController.queryUserList(
          {
            current: params.current ?? 1,
            pageSize: params.pageSize ?? 10,
            keyword: params.keyword ?? '',
          },
          options,
        );

        setData(userList);
        return userList;
      } catch (err) {
        setError(err as Error);
        // 抛出错误以便调用方处理
        throw err;
      } finally {
        setLoading(false);
      }
    },
    [UserController],
  );

  // 初始化加载数据
  useEffect(() => {
    fetchUserList();
  }, [fetchUserList]);

  return {
    data,
    loading,
    error,
    // 暴露出去以便手动触发
    fetchUserList,
  };
};
